package org.example.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.example.order.mapper.OrderTblMapper;
import org.example.order.model.OrderTbl;
import org.example.order.openFeign.AccountOpenFeignClient;
import org.example.order.openFeign.StorageOpenFeignClient;
import org.example.order.service.OrderTblService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderTblServiceImpl extends ServiceImpl<OrderTblMapper, OrderTbl>
        implements OrderTblService {

    @Autowired
    private OrderTblMapper orderTblMapper;

    @Autowired
    private AccountOpenFeignClient accountOpenFeignClient;

    @Autowired
    private StorageOpenFeignClient storageOpenFeignClient;

    @Override
    @Transactional
    @GlobalTransactional
    public void create(Integer accountId, String commodityCode, int count) {
        //本次订单共计消费金额
        int orderMoney = calculate(commodityCode, count);
        //生成订单后需要更细用户表中对应的金额
        accountOpenFeignClient.updateAccount(accountId, orderMoney);
        //更新仓库剩余商品数量
        storageOpenFeignClient.updateStorage(commodityCode, count);

        OrderTbl orderTbl = new OrderTbl();
        orderTbl.setUserId(String.valueOf(accountId));
        orderTbl.setCommodityCode(commodityCode);
        orderTbl.setCount(count);
        orderTbl.setMoney(orderMoney);
        orderTblMapper.insert(orderTbl);
    }

    private int calculate(String commodityCode, int count) {
        return 200 * count;
    }
}
